import userBaseApi from '@/comment/apis/user/Auth';
import util from '@/comment/Util';
// import Request from '@/comment/Request';

export default {
    state: {
        userInfo: {},
        loginStatus: false,
        accessToken: undefined,
        expiresIn: undefined
    },
    mutations: {
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
        },
        setLoginStatus(state, loginStatus) {
            state.loginStatus = loginStatus;
        },
        setAccessToken(state, accessToken) {
            state.accessToken = accessToken;
            // Request.defaults.headers['Authorization'] = "Bearer " + accessToken;
        },
        setExpiresIn(state, expiresIn) {
            state.expiresIn = expiresIn;
        },
        logout(state) {
            state.userInfo = {};
            state.expiresIn = undefined;
            state.accessToken = undefined;
            state.loginStatus = false;
        }
    },
    actions: {
        async login({commit}, params) {
            return await userBaseApi.authToken(params).then(async res => {
                return await util.handelHttpResponse(res).then(async ({data}) => {
                    commit('setAccessToken', data.access_token);
                    let expiresIn = data.expires_in * 1000 + new Date().getTime() + 10000;
                    commit('setExpiresIn', expiresIn);
                    return true;
                }).catch(async () => false)
            }).catch(async () => false);
        }
    },
    getters: {
        userInfo: s => s.userInfo,
        loginStatus: s => s.loginStatus,
        accessToken: s => s.accessToken,
        expiresIn: s => s.expiresIn
    }
}